package com.ideyatech.errorhandling.service;

import com.ideyatech.errorhandling.dao.GroupAuthorityDao;
import com.ideyatech.errorhandling.dao.GroupDao;
import com.ideyatech.errorhandling.dao.UserDao;
import com.ideyatech.errorhandling.entity.Group;
import com.ideyatech.errorhandling.entity.GroupAuthority;
import com.ideyatech.errorhandling.entity.User;

public class InitServiceImpl implements InitService {
	private UserDao userDao;
	private GroupAuthorityDao groupAuthorityDao;
	private GroupDao groupDao;
	private boolean isInitialized = false;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ideyatech.errorhandling.service.InitService#init()
	 */
	@Override
	public void init() {
		if (!isInitialized)
			doInit();
	}

	private void doInit() {
		User brent = new User();
		brent.setUsername("brent");
		brent.setPassword("b4d02e2460d370291fa0fc80127d1d7b30fa3cd7ceaf134383ef9829448946ac");
		userDao.mergeEntity(brent);

		User adrian = new User();
		adrian.setUsername("adrian");
		adrian.setPassword("c23ad6f18412014673b2d04794ca038ef6767fe94afe408dffb775362fe07e68");
		userDao.mergeEntity(adrian);

		User zach = new User();
		zach.setUsername("zach");
		zach.setPassword("cb9b5a0f4b09ba490e3acc902f38acf85205797cd59654645e5c1ef8c1ada0");
		userDao.mergeEntity(zach);

		GroupAuthority canAdd = new GroupAuthority();
		canAdd.setAuthority("CAN_ADD");
		groupAuthorityDao.mergeEntity(canAdd);

		GroupAuthority canAssign = new GroupAuthority();
		canAssign.setAuthority("CAN_ASSIGN");
		groupAuthorityDao.mergeEntity(canAssign);

		GroupAuthority canView = new GroupAuthority();
		canView.setAuthority("CAN_VIEW");
		groupAuthorityDao.mergeEntity(canView);

		Group admins = new Group();
		admins.setName("ADMINS");
		admins.addMember(brent);
		admins.addAuthority(canAdd);
		admins.addAuthority(canAssign);
		admins.addAuthority(canView);
		groupDao.mergeEntity(admins);

		Group editors = new Group();
		editors.setName("EDITORS");
		editors.addMember(adrian);
		editors.addAuthority(canAdd);
		editors.addAuthority(canView);
		groupDao.mergeEntity(editors);

		Group ordinaryUsers = new Group();
		ordinaryUsers.setName("USERS");
		ordinaryUsers.addMember(zach);
		ordinaryUsers.addAuthority(canView);
		groupDao.mergeEntity(ordinaryUsers);

		isInitialized = true;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setGroupAuthorityDao(GroupAuthorityDao groupAuthorityDao) {
		this.groupAuthorityDao = groupAuthorityDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}
}
